package apptoko.com.adapter;

import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import apptoko.com.UILApplication;
import apptoko.com.model.ContentItemInfo;

import com.androidquery.AQuery;
import apptoko.com.R;

public class CollectionItemAdapter extends ArrayAdapter<ContentItemInfo>{
	
	private LayoutInflater inflater;
	private AQuery aq;
	public CollectionItemAdapter(Context context, int resource, List<ContentItemInfo> objects) {
		super(context, resource, objects);
		// TODO Auto-generated constructor stub
		inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		ViewHolder holder = null;
		if(convertView == null){
			convertView = inflater.inflate(R.layout.collection_item, null);
			holder = new ViewHolder();
			holder.icon = (ImageView) convertView.findViewById(R.id.coll_icon);
			holder.price = (TextView) convertView.findViewById(R.id.coll_price);
			holder.title = (TextView) convertView.findViewById(R.id.coll_name);
			holder.rating = (RatingBar) convertView.findViewById(R.id.coll_rating);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		ContentItemInfo item = getItem(position);
		if(item != null){
			aq = new AQuery(convertView);
			if(UILApplication.getInstance().isLoadAllImgs()){
				aq.id(holder.icon).visible();
				if(aq.getCachedFile(item.getAvatar())!=null){
					aq.id(holder.icon).image(aq.getCachedFile(item.getAvatar()),75);
					Log.e("NMN","load collection items from cachedFile");
				}else{
					Log.e("NMN","load collection items from server");
					Bitmap placeholder = aq.getCachedImage(R.drawable.image_loading);
					aq.id(holder.icon).image(item.getAvatar(), false, true, 0, 0, placeholder, AQuery.FADE_IN_NETWORK);
				}
				
			}else{
				aq.id(holder.icon).visibility(View.GONE);
			}
			int price = item.getPrice();
			if(price == 0){
				aq.id(holder.price).text(R.string.free);
			} else {
				aq.id(holder.price).text(String.valueOf(price));
			}
			aq.id(holder.title).text(item.getTitle());
			aq.id(holder.rating).rating(item.getRating());
		}
		return convertView;
	}
	
	private static class ViewHolder {
		ImageView icon;
		TextView price;
		TextView title;
		RatingBar rating;
	}
}
